package com.hk.websocket;

import cn.hutool.json.JSONUtil;
import com.hk.enums.PictureEditMessageTypeEnum;
import com.hk.model.vo.user.UserVO;
import com.hk.websocket.distuptor.PictureEditEvent;
import com.hk.websocket.model.PictureEditPushVO;
import com.hk.websocket.model.PictureEditRequestMessage;
import com.lmax.disruptor.WorkHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

/**
 * @author 20231
 */
@Slf4j
@Component
public class PictureEditEventWorkHandler implements WorkHandler<PictureEditEvent> {

    @Resource
    @Lazy
    private PictureEditHandler pictureEditHandler;

    /**
     *
     * @param event
     * @throws Exception
     */
    @Override
    public void onEvent(PictureEditEvent event) throws Exception {
        PictureEditRequestMessage pictureEditRequestMessage = event.getPictureEditRequestMessage();
        WebSocketSession session = event.getSession();
        UserVO user = event.getUser();
        Long pictureId = event.getPictureId();
        // 获取到消息类别
        String type = pictureEditRequestMessage.getType();
        PictureEditMessageTypeEnum pushEnum = PictureEditMessageTypeEnum.valueOf(type);
        // 调用对应的消息处理方法
        switch (pushEnum) {
            case ENTER_EDIT -> pictureEditHandler.handleEnterEditMessage(pictureEditRequestMessage, session, user, pictureId);
            case EDIT_ACTION -> pictureEditHandler.handleEditActionMessage(pictureEditRequestMessage, session, user, pictureId);
            case EXIT_EDIT -> pictureEditHandler.handleExitEditMessage(pictureEditRequestMessage, session, user, pictureId);
            default -> {
                PictureEditPushVO pictureEditPushVO = new PictureEditPushVO();
                pictureEditPushVO.setType(PictureEditMessageTypeEnum.ERROR.getValue());
                pictureEditPushVO.setMessage("消息类型错误");
                pictureEditPushVO.setUserVO(user);
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(pictureEditPushVO)));
            }

        }
    }
}
